package org.dualr.litelog.dao;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.dualr.litelog.entity.Tag;

public class TagDao {
	private static TagDao _instance = null;

	public static TagDao getInstance() {
		if (_instance == null) {
			_instance = new TagDao();
		}
		return _instance;
	}

	public String insert(Tag tag) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(tag);
		} finally {
			pm.close();
		}
		return tag.getId().toString();
	}

	// delete by id
	public boolean deleteById(Long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Tag Tag = pm.getObjectById(Tag.class, id);
		pm.deletePersistent(Tag);
		pm.close();
		return true;
	}

	// get all Tag
	@SuppressWarnings("unchecked")
	public List<Tag> getAll() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Tag.class);
		List<Tag> Tag = null;
		try {
			Tag = (List<Tag>) query.execute();
			return Tag;
		} finally {
			query.closeAll();
		}
	}

	@SuppressWarnings("unchecked")
	public Long checkTag(String tag) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Tag.class);
		query.setFilter("tag == tagParam");
		query.declareParameters("String tagParam");
		List<Tag> tagList = (List<Tag>) pm.newQuery(query).execute(tag);
		if (tagList.size() == 0) {
			return Long.parseLong("0");
		}else{
			return tagList.get(0).getId();
		}
	}
	//update counts
	public void updateTagCount(Long id, String type) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			if(type.equals("increment")){
				Tag tag = pm.getObjectById(Tag.class, id);
				tag.setCount(tag.getCount() + 1);
			}else{
				Tag tag = pm.getObjectById(Tag.class, id);
				tag.setCount(tag.getCount() - 1);
			}
		} finally {
			pm.close();
		}
	}
}
